package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户模块控制层
 * @author wangxin
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = null;
        try {
            pageResult = userService.findPage(
                    queryPageBean.getCurrentPage(),
                    queryPageBean.getPageSize(),
                    queryPageBean.getQueryString()
            );
            return pageResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //添加用户
    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody User user, Integer[] roleIds){
        try {
            /*密码加密*/
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setPassword(encoder.encode(user.getPassword()));
            userService.add(user,roleIds);

            return new Result(true,MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
    }

    //删除用户
    @RequestMapping("/deleteById")
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result deleteById(Integer userId){
        try {
            userService.deleteById(userId);

            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
    }

    //根据id查询用户信息
    @RequestMapping("/findById")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findById(Integer userId){
            User user = userService.findById(userId);

            if (user != null) {
                /*不回显密码*/
                user.setPassword("");
                return new Result(true,MessageConstant.GET_USER_SUCCESS,user);
            }

            return new Result(false,MessageConstant.GET_USER_FAIL);
    }

    //根据用户id查询角色id集合
    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer userId){
        try {
            List<Integer> list = userService.findRoleIdsByUserId(userId);

            return new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ROLE_FAIL);
        }

    }

    //编辑用户信息
    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result edit(@RequestBody User user,Integer[] roleIds){
        try {
            if (user.getPassword() != null && user.getPassword().length() > 0){
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                user.setPassword(encoder.encode(user.getPassword()));
            }
            userService.edit(user,roleIds);

            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }

    }

    /**
     * 获取当前登录用户的用户名
     */
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //.getContext().安全容器对象
        //getAuthentication():认证对象
        //.getPrincipal();当前用户对象 user
        try {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }


    //根据用户名获取菜单
    @RequestMapping("/getmenu")
    public Result getmenu(@RequestParam("username") String username){
        try {
            List<Menu> resultList=userService.getmenus(username);
            return new Result(true,MessageConstant.GET_MENU_SUCCESS,resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MENU_FAIL);
        }
    }
}
